#include <iostream>
#include <fstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MULTICAST_GROUP "239.255.255.250"
#define PORT 8888
#define BUFFER_SIZE 1024

int main()
{
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        perror("socket");
        return 1;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(PORT);
    bind(sock, (struct sockaddr *)&addr, sizeof(addr));

    struct ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));

    std::ofstream file("received_file.bin", std::ios::binary);
    char buffer[BUFFER_SIZE];
    while (true)
    {
        ssize_t bytes_recv = recv(sock, buffer, BUFFER_SIZE, 0);
        if (bytes_recv <= 0)
            break;

        if (bytes_recv == 3 && strncmp(buffer, "END", 3) == 0)
            break;

        file.write(buffer, bytes_recv);
    }

    file.close();
    close(sock);
    return 0;
}